package pictureview;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 对PictureView类进行封装
 * 实现代码的可读，可重用，可扩展
 */
public class PictureView extends JPanel {
    public PictureView() {
        //图片只需要加载一次，放在paintComponent中会被反复执行，所以应该把他放到构造方法中，只需加载一次
        File file = new File(pathname);
        System.out.println(pathname);
        try {
            System.out.println("加载图片");
            this.image = ImageIO.read(file);
            //g.drawImage(image,x,y,width,height,observer)
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    //添加属性，背景颜色
    private Color bgColor;

    //添加属性，自定义图片
    private BufferedImage image;
    String pathname = "Java-swing\\data\\1.jpg";

    public void setBackgroundColor(Color color) {
        this.bgColor = color;
        //更换颜色后需要repaint
        this.repaint();
    }

    public void setImagePath(String pathname){
        this.pathname = pathname;
        System.out.println(pathname+"被执行");
        //PictureView只会执行一次
        File file = new File(pathname);
        System.out.println(pathname);
        try {
            this.image = ImageIO.read(file);
            //g.drawImage(image,x,y,width,height,observer)
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        this.repaint();
    }





    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        //设置背景
        int width = getWidth();
        int height = getHeight();
        if (bgColor != null) {
            g.setColor(bgColor);
            g.fillRect(0, 0, width, height);
        }else{
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, height);

        }

//        File file = new File("Java-swing\\data\\1.jpg");
//        try {
//            BufferedImage image= ImageIO.read(file);
//            //g.drawImage(image,x,y,width,height,observer)
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        int imgW = image.getWidth();
        int imgH = image.getHeight();

        int fitW = width;
        int fitH = width * imgH / imgW;
        if (fitH > height) {
            fitH = height;
            fitW = height * imgW / imgH;
        }

        int fitX = (width - fitW) / 2;
        int fitY = (height - fitH) / 2;
        g.drawImage(image, fitX, fitY, fitW, fitH, null);
    }
}
